package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.AdvertComponent;
import com.dy.lock.screen.constants.Constant;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.AdvertCollectInfo;
import com.dy.lock.screen.pojo.AdvertInfo;
import com.dy.lock.screen.pojo.AdvertTagRelationInfo;
import com.dy.lock.screen.pojo.MaterialInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.AdvertCollectService;
import com.dy.lock.screen.service.AdvertOperatorService;
import com.dy.lock.screen.service.AdvertService;
import com.dy.lock.screen.service.CustomerTagService;
import com.dy.lock.screen.service.MaterialService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.utils.DateUtil;
import com.dy.lock.screen.vo.AdvertOperateTypeVo;
import com.dy.lock.screen.vo.AdvertResultVo;
import com.dy.lock.screen.vo.AdvertVo;
import com.google.gson.Gson;

@Component("advertComponent")
public class AdvertComponentImpl implements AdvertComponent {

	private static final Logger log = Logger
			.getLogger(AdvertComponentImpl.class);
	@Resource(name = "advertService")
	private AdvertService advertService;
	@Resource(name = "customerTagService")
	private CustomerTagService customerTagService;
	@Resource(name = "advertCollectService")
	private AdvertCollectService advertCollectService;
	@Resource(name = "advertOperatorService")
	private AdvertOperatorService advertOperatorService;
	@Resource(name = "materialService")
	private MaterialService materialService;

	private Gson gson;

	public AdvertComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public AdvertVo getAdvertInfo(String body, Head head) throws Exception {
		try {
			AdvertVo vo = gson.fromJson(body, AdvertVo.class);
			if (vo != null) {
				String userId = vo.getUserId();
				String haveAdStr = vo.getHaveAds();
				int needAdCount = vo.getNeedAdCount();
				List<AdvertOperateTypeVo> adOpType = vo.getAdOptList();
				int optResult = this.advertOperatorService.saveBatch(adOpType,
						userId, head);
				if (optResult < 0) {
					throw new ServerDisponseException(
							TransmissionCode.OPERATOR_EXCEPTION.getCode(),
							TransmissionCode.OPERATOR_EXCEPTION.getMessage());
				}
				List<AdvertInfo> adList = null;
				List<String> tags = this.customerTagService
						.queryTagByCustomerId(userId);
				List<String> adIds = null;
				if (tags != null && !tags.isEmpty()) {
					Map<String, Object> tagsMap = new HashMap<String, Object>();
					tagsMap.put("adTagIds", tags);
					adIds = this.advertService.queryByAdTag(tagsMap);
				}
				Map<String, Object> adIdMap = new HashMap<String, Object>();
				if (StringUtils.isBlank(haveAdStr)) {
					adIdMap.put("adIdsIn", adIds);
					adList = this.advertService.queryAll(adIdMap, head);
				} else {
					String[] haveAdArr = haveAdStr.split(",");
					// 查询可以发送给前端的广告信息
					adIdMap.put("adIdsIn", adIds);
					adIdMap.put("adIds", Arrays.asList(haveAdArr));
					adList = this.advertService.queryByAdIds(adIdMap, head);
				}
				Map<String, Object> map = new HashMap<String, Object>();
				List<String> delAdIds = new ArrayList<String>();
				if (StringUtils.isNotBlank(haveAdStr)) {
					String[] haveAdArr = haveAdStr.split(",");
					map.put("adIds", Arrays.asList(haveAdArr));
					delAdIds = this.advertService.queryWillDeleteId(map);
				}
				AdvertVo adVo = this.convert(adList, needAdCount, userId, head);
				if (adVo != null) {
					adVo.setDelAdIds(delAdIds);
					return adVo;
				}
				return new AdvertVo();
			} else {
				log.info("requestId:" + head.getRequestId()
						+ ",获取广告信息时，报文解析异常。");
				throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
						.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
			}
		} catch (Exception e) {
			log.error("获取广告异常", e);
			return new AdvertVo();
		}

	}

	/**
	 * 把从数据库中查询到的数据转化为需要传输的对象
	 * 
	 * @param adList
	 * @param needAdCount
	 * @param userId
	 * @return
	 */
	private AdvertVo convert(List<AdvertInfo> adList, int needAdCount,
			String userId, Head head) {
		AdvertVo adVo = new AdvertVo();
		List<AdvertResultVo> resultVos = new ArrayList<AdvertResultVo>();
		if (adList != null && !adList.isEmpty()) {
			int need = adList.size() < needAdCount ? adList.size()
					: needAdCount;
			for (int i = 0; i < need; i++) {
				AdvertResultVo resultVo = new AdvertResultVo();
				AdvertInfo adInfo = adList.get(i);
				resultVo.setAdId(adInfo.getAdId());
				resultVo.setAdTitle(adInfo.getAdTitle());
				resultVo.setAdType(adInfo.getAdType());
				List<AdvertTagRelationInfo> tags = this.advertService
						.queryByAdId(adInfo.getAdId(), head);
				if (tags != null && !tags.isEmpty()) {
					resultVo.setAdIconIndex(tags.get(0).getAdTagId());
				}
				String[] picPaths = adInfo.getAdPicPath().split(";");
				if (picPaths != null) {
					String[] adUrls = new String[picPaths.length];
					for (int j = 0; j < picPaths.length; j++) {
						adUrls[j] = CommonUtil.getUrlPrefix() + picPaths[j];
					}
					resultVo.setAdUrls(adUrls);
				}

				if (Constant.ADVERT_CPM.equals(adInfo.getAdType())) { // CPM
					double price = adInfo.getAdPrice();
					int needShowCount = 0;
					if (price == 0) {
						double[] rightScoreRule = { 0, 0, 0, 0 };
						resultVo.setRightScoreRule(rightScoreRule);
					} else if (price > 0 && price < 2) {
						needShowCount = (int) (Constant.USER_GET_SCORE / price);
						if (needShowCount == 2) {
							double[] rightScoreRule = { 0, 2, 0, 2 };
							resultVo.setRightScoreRule(rightScoreRule);
						} else if (needShowCount == 4) {
							double[] rightScoreRule = { 0, 0, 0, 2 };
							resultVo.setRightScoreRule(rightScoreRule);
						}
					} else if (price >= 2) {
						double[] rightScoreRule = { price, price, price, price };
						resultVo.setRightScoreRule(rightScoreRule);
					}
					resultVo.setNeedShowCount(4);
					resultVo.setLeftScore(0);

				} else {// CPC
					resultVo.setLeftScore(adInfo.getAdPrice().intValue());
				}
				if (StringUtils.isNotBlank(adInfo.getLeftSlideUrl())) {
					resultVo.setLeftUrl(adInfo.getLeftSlideUrl());
				} else {
					String materialId = adInfo.getMaterialId();
					MaterialInfo maInfo = this.materialService
							.queryByPrimaryKey(materialId);
					if (maInfo != null) {
						resultVo.setLeftUrl(maInfo.getMaterialMain());
					}
				}

				AdvertCollectInfo collect = this.advertCollectService
						.queryByAdAndUser(adInfo.getAdId(), userId, head);
				if (collect != null) {
					resultVo.setCollect(true);
				} else {
					resultVo.setCollect(false);
				}
				resultVos.add(resultVo);

			}
		}
		adVo.setAdList(resultVos);
		adVo.setDate(DateUtil.formatTime(new Date()));
		return adVo;
	}

	@Override
	public boolean operateAdvertRecord(String body, Head head) throws Exception {
		AdvertVo vo = gson.fromJson(body, AdvertVo.class);
		if (vo != null) {
			String userId = vo.getUserId();
			List<AdvertOperateTypeVo> adOpType = vo.getAdOptList();
			int optResult = this.advertOperatorService.saveBatch(adOpType,
					userId, head);
			if (optResult >= 0) {
				return true;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.OPERATOR_EXCEPTION.getCode(),
						TransmissionCode.OPERATOR_EXCEPTION.getMessage());
			}

		} else {
			log.info("requestId:" + head.getRequestId() + ",广告操作记录时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}
}
